import { request } from '@/plugins/http';
import { CurrentAccountInfo } from '@/app';
import { ke } from '@/plugins/ke';

// 获取当前登录信息
export const apiGetCurrentInfo = () => {
  return request('admin/account/current');
}

// 登录
export const apiAccountLoginApi = (data: {
  username: string,
  password: string
}) => {
  return request('admin/account/login', {
    method: 'POST',
    data
  }).then(res => {
    if (res.success) {
      localStorage.setItem('login_token', res.data.access_token);

      localStorage.setItem('login_expire', (ke.getTimestamp() + res.data.expire_in).toString());
    }
    return res;
  })
}

// 修改用户信息
export const apiAccountEditInfo = (data: CurrentAccountInfo) => {
  return request('admin/account/edit_info', {
    method: 'POST',
    data
  })
}

// 修改用户密码
export const apiAccountEditPass = (data: { old: string, new: string }) => {
  return request('admin/account/edit_pass', {
    method: 'POST',
    data
  }).then(res => {
    if (res.status) {
      localStorage.removeItem('login_token');
      localStorage.removeItem('login_expire');
    }
    return res;
  })
}

// 修改用户头像
export const apiAccountEditAvatar = (file: File) => {
  const fd = new FormData();
  fd.append('file', file);
  return request('admin/account/edit_avatar', {
    method: 'POST',
    data: fd,
  })
}

// 刷新令牌有效时间
export const apiAccountRefreshToken = () => {
  return request('admin/account/refresh_token', {
    method: 'POST'
  });
}

// 退出登录
export const apiAccountLogout = () => {
  return request('admin/account/logout', { method: 'POST' }).then(res => {
    if (res.status) {
      localStorage.removeItem('login_token');
      localStorage.removeItem('login_expire');
    }
    return res;
  })
}
